package xdu.lz.stage5_jucUtils.chapter4_semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created at 2019/10/19 0019 下午 3:38
 *
 * 连接池拒绝策略：当获取连接池，连接数已经满
 * 1、直接抛异常
 * 2、尝试等待 n ms ， 然后抛异常
 * 3、阻塞，直到有可用连接
 * 4、直接丢弃连接请求
 * 5、注册一个回调函数，让有可用连接，回调通知。本质是注册一个runnable，当完成后执行runnable.run
 */

public class SemaphoreAPI {



    public static void main(String[] args) throws InterruptedException {

        final Semaphore semaphore = new Semaphore(2);
        //1 acquire,一次可以acquire多个，抛中断异常
        semaphore.acquire();
        semaphore.acquire(10);
        // current available permits
        semaphore.availablePermits();

        //2 acquire,无法被中断，没有中断异常
        semaphore.acquireUninterruptibly();
        semaphore.acquireUninterruptibly(10);
        //3 获取剩下的所有许可证
        semaphore.drainPermits();
        //3 tryget
        semaphore.tryAcquire();
        semaphore.tryAcquire(10);
        semaphore.tryAcquire(10, TimeUnit.HOURS);
        semaphore.tryAcquire(10,10, TimeUnit.HOURS);
        //4 release
        semaphore.release();
        semaphore.release(10);
        //5 blocked thread
        //当前被block的线程集合,是protected的，需要继承才能使用
        //chapter4_semaphore.getQueuedThreads();
        //是否有block的线程,block线程的数量
        semaphore.getQueueLength();
        semaphore.hasQueuedThreads();
    }

}
